from threading import Thread
import time

class Timer(Thread):
	def __init__(self, timeout = 1, initial = False):
		Thread.__init__(self)
		self.timeout = timeout
		self._timeoutCallbacks = []
		self.terminated = False
		self.initial = initial

	def registerTimeoutCallback(self, callback):
		self._timeoutCallbacks.append(callback)

	def onTimeout(self):
		stamp = time.time()
		for callback in self._timeoutCallbacks:
			callback(stamp)

	def start(self):
		if self.initial:
			self.onTimeout()
		while not self.terminated:
			time.sleep(self.timeout)
			self.onTimeout()

	def stop(self):
		self.terminated = True
